package logic.ships;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.slots.AbstractSlotCreator;
import logic.weapons.WeaponSlot;
import logic.weapons.WeaponType;

import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;

public class WeaponSlotsCreator extends AbstractSlotCreator {
	
	private final String SOCKET = "socket";
	private final String FRONT = "front";
	private final String HEATSEAKER = "heatseaker";
	private final String MISSILE = "missile";
	private final String ARTILLARY = "artillary";
	private final String ENERGY = "energy";
	
	private HashMap<WeaponType, List<WeaponSlot>> slots;
	private HashMap<String, TriMesh> sockets, fronts;
	private HashMap<String, String> types;
	
	private Ship ship;
	
	public WeaponSlotsCreator(Ship ship) {
		this.ship = ship;
		
		slots = new HashMap<WeaponType, List<WeaponSlot>>();
		
		sockets = new HashMap<String, TriMesh>();
		fronts = new HashMap<String, TriMesh>();
		types = new HashMap<String, String>();
		
		init(ship.getLowQualityNode());
		createWeaponSlots();
	}
	
	private void init(Node parent) {
		for(Spatial child : parent.getChildren()) {
			if(child instanceof Node) init((Node)child);
			else if(child instanceof TriMesh) {
				TriMesh mesh = (TriMesh)child;
				String name = mesh.getName();
				String[] array = name.split("_");
				if(array.length != 2) continue;
				name = array[0];
				String type = getType(name);
				if(type == null) continue;
				
				String position = array[1];
				if(position.equals(SOCKET)) sockets.put(name, mesh);
				else if(position.equals(FRONT)) fronts.put(name, mesh);
				else continue;
				types.put(name, type);
			}
		}
	}
	
	private String getType(String name) {
		if(name.startsWith(ENERGY)) return ENERGY;
		if(name.startsWith(HEATSEAKER)) return HEATSEAKER;
		if(name.startsWith(MISSILE)) return MISSILE;
		if(name.startsWith(ARTILLARY)) return ARTILLARY;
		return null;
	}
	
	private void createWeaponSlots() {
		for(String name : types.keySet()) {
			String type = types.get(name);
			
			TriMesh socket = sockets.get(name);
			TriMesh front = fronts.get(name);
			
			WeaponSlot slot = new WeaponSlot(socket, front, ship);
			ship.attachChild(slot);
			
			WeaponType weaponType = WeaponType.Energy;
			if(type.equals(HEATSEAKER)) weaponType = WeaponType.HeatSeeker;
			else if(type.equals(MISSILE)) weaponType = WeaponType.Missile;
			else if(type.equals(ARTILLARY)) weaponType = WeaponType.Artillary;
			
			List<WeaponSlot> weaponSlots = slots.get(weaponType);
			if(weaponSlots == null) weaponSlots = new ArrayList<WeaponSlot>();
			
			weaponSlots.add(slot);
			slots.put(weaponType, weaponSlots);
		}
	}
	
	public HashMap<WeaponType, List<WeaponSlot>> getWeaponSlots() { return slots; }
}